package com.office.chatAi.service;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DeepSeekChatService {

    private static final String API_KEY="sk-e8529cf000c343caab18b107d3c1433b";
    private static final String API_URL="https://api.deepseek.com/chat/completions";
//   #DOTO 没有存储问询记录
    JSONArray message = new JSONArray();
    public String sendMessage(String text) throws IOException {
        // 创建请求JSON数据
        JSONObject payload = new JSONObject();
        JSONObject userRole = new JSONObject();
        userRole.put("role", "user");
        userRole.put("content", text);
        message.add(userRole);

        payload.put("model", "deepseek-chat");
        payload.put("messages", message);
        payload.put("stream", false);
        System.out.println("payload: " + payload.toString());
        // 初始化HttpClient和HttpPost
        HttpClient client = HttpClients.createDefault();
        HttpPost postMethod = new HttpPost(API_URL);

        // 设置请求头
        postMethod.setHeader("Content-Type", "application/json");
        postMethod.setHeader("Authorization", "Bearer " + API_KEY);

        // 设置请求体为JSON数据
        StringEntity entity = new StringEntity(payload.toString(), StandardCharsets.UTF_8);
        postMethod.setEntity(entity);

        // 执行请求
        HttpResponse response = client.execute(postMethod);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new RuntimeException("抱歉，请求失败 " + statusCode);
        }

        // 获取响应并分析
        String responseString = EntityUtils.toString(response.getEntity());
        JSONObject responseJson = JSONObject.parseObject(responseString);
        JSONObject content = responseJson.getJSONArray("choices").getJSONObject(0).getJSONObject("message");
        return content.getString("content");
    }
}